import {defineStore} from 'pinia';
import {ref} from 'vue';
import {GetMenu} from '@/api/auth.js'
import {useRouter,useRoute} from 'vue-router';
const modulesR = import.meta.glob(`../views/**/*.vue`)
// import HomeView from '../views/HomeView.vue'
 
export const useMenu = defineStore("menu",()=>{
  // 菜单
  const menu = ref([]);
  // admin的子路由
  const route = ref([]);
  const router = useRouter();
  const position = ref([]);
 
  // 定义获取路由的方法
  const getMenu = ()=>{
    const $route = useRoute();
    GetMenu()
    .then(res=>{
      if(res.data.code==0){
        menu.value =  res.data.list;   
        route.value = res.data.route.map(item=>({path:item.path,component:modulesR['../views'+item.component]}))
        // route.value = res.data.route.map(item=>({path:item.path,component:()=>import('../views'+item.component)}))
        // 动态路由
        // 获取admin路由
        const admin = router.getRoutes()[2];
        // console.log("admin",admin)
        // 修改子路由
        admin.children = route.value;
        // 动态添加路由
        router.addRoute(admin);
        // 跳转都当前路由
        router.replace($route.path)
        
      }
        
    })
  }
  const getPosition = (list,path,parent=null)=>{
    var parentList = [];
     for(var i=0;i<list.length;i++){
      if(list[i].children){
          parentList.concat(getPosition(list[i].children,path,list[i]))
      }else{
        if(path==list[i].path){
          if(parent){
            parentList.push(parent);
          }
         
          parentList.push(list[i]);
        }
      }
     }
     return parentList;


  }

  return {menu,route,getMenu,position,getPosition}
})